﻿using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic.CT_NBIoT;
using Atmk.WaterMeter.MIS.Datas;
using Microsoft.Extensions.Hosting;
using NLog;

namespace Atmk.WaterMeter.MIS.TimedTask
{
    public class OpenValveService : IHostedService
    {
        private static readonly Logger _Logger = LogManager.GetCurrentClassLogger();
        private readonly ICT_PlatformDeviceInfoLogic _deviceLogic;
        private Timer _timer;

        public OpenValveService(ICT_PlatformDeviceInfoLogic deviceLogic)
        {
            _deviceLogic = deviceLogic;
        }

        #region Implementation of IHostedService

        /// <summary>
        ///     Triggered when the application host is ready to start the service.
        /// </summary>
        /// <param name="cancellationToken">Indicates that the start process has been aborted.</param>
        public Task StartAsync(CancellationToken cancellationToken)
        {
            ThreadPool.QueueUserWorkItem((state)=>
            {
                //1. 回调的方法
                //2. 回调方法的参数
                //3. 调用方法之前要延迟的时间量
                //4. 每次调用之间的时间间隔
                _timer = new Timer(RunOnce, null, TimeSpan.FromHours(3), TimeSpan.FromHours(6));
                //_timer = new Timer(RunOnce, null, TimeSpan.FromSeconds(1), TimeSpan.FromMinutes(1));
                _Logger.Info($"{nameof(OpenValveService)}-Timer启动");
            });
            return Task.Delay(5, cancellationToken);
        }

        /// <summary>
        ///     Triggered when the application host is performing a graceful shutdown.
        /// </summary>
        /// <param name="cancellationToken">Indicates that the shutdown process should no longer be graceful.</param>
        public Task StopAsync(CancellationToken cancellationToken)
        {
            if (_timer != null)
            {
                _timer.Dispose();
                _timer = null;
            }
            return Task.Delay(5, cancellationToken);
        }

        private async void RunOnce(object state)
        {
            //检查
            _Logger.Debug($"本次批量开阀时间:{DateTime.Now:yyyy/MM/dd HH:mm:ss}");
            try
            {
                using (var context = ContextBuilder.Build())
                {
                    var ids = context.Meter.Select(m => m.CtdeviceId).ToArray();
                    //ids = new[] {"8a61a230-f208-4421-ad40-4bfb2259c9dd", "5a5832ea-871d-4169-97f4-8c964fc74f09"};
                    await _deviceLogic.BatchOpenValve(ids);
                }
            }
            catch (Exception ex)
            {
                _Logger.Error("定时开阀error：" + ex.Message);
            }
        }

        #endregion
    }
}